﻿using Microsoft.AspNetCore.DataProtection;
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using ViazyNetCore.Identity.WeChat;

namespace Microsoft.AspNetCore.Authentication.WeChat
{
    public static class WeChatOAuthExtensions
    {
        public static AuthenticationBuilder AddWeChatOAuth(this AuthenticationBuilder builder)
            => builder.AddWeChatOAuth(WeChatVarConst.AuthenticationScheme, _ => { });

        public static AuthenticationBuilder AddWeChatOAuth(this AuthenticationBuilder builder, Action<WeChatOptions> configureOptions)
            => builder.AddWeChatOAuth(WeChatVarConst.AuthenticationScheme, configureOptions);

        public static AuthenticationBuilder AddWeChatOAuth(this AuthenticationBuilder builder, string authenticationScheme, Action<WeChatOptions> configureOptions)
            => builder.AddWeChatOAuth(authenticationScheme, WeChatVarConst.DisplayName, configureOptions);


        public static AuthenticationBuilder AddWeChatOAuth(this AuthenticationBuilder builder, string authenticationScheme, string displayName, Action<WeChatOptions> configureOptions)
        {
            builder.Services.TryAddTransient<ISecureDataFormat<AuthenticationProperties>>((provider) =>
            {
                var dataProtectionProvider = provider.GetRequiredService<IDataProtectionProvider>();
                var distributedCache = provider.GetRequiredService<IDistributedCache>();

                var dataProtector = dataProtectionProvider.CreateProtector(
                    typeof(WeChatOAuthHandler).FullName!,
                    typeof(string).FullName!, WeChatVarConst.AuthenticationScheme,
                    "v1");

                var dataFormat = new CachedPropertiesDataFormat(distributedCache, dataProtector);
                return dataFormat;
            });


            return builder.AddOAuth<WeChatOptions, WeChatOAuthHandler>(authenticationScheme,
                displayName, configureOptions);
        }



    }
}
